package org.dizena.common.interaction.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Objects;

@RestControllerAdvice
public class ResultVOAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        boolean a = returnType.getParameterType().isAssignableFrom(ResultVO.class);
        boolean b = returnType.hasMethodAnnotation(NoResultVOAdvice.class);
        boolean c = returnType.getDeclaringClass().getName().contains("springfox");
        boolean d = Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(NoResultVOAdvice.class);

        return !a && !b && !c && !d;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 判断请求是否来自Knife4j
        String uri = request.getURI().toString();
        if (uri.contains("/api-docs") || uri.contains("/swagger-resources")) {
            return body;
        } else {
            if (body == null) {
                return ResultVO.success();
            } else {
                Type type = returnType.getGenericParameterType();
                if (type.equals(String.class)) {
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return toJsonStr(ResultVO.success(body));
                } else if (type.equals(ResultVO.class)) {
                    return body;
                } else if (type.equals(ResponseEntity.class)) {
                    ResponseEntity entity = (ResponseEntity) body;
                    return ResultVO.success(entity.getBody());
                } else if (type.equals(byte[].class) || type.equals(Byte[].class)) {
                    return body;
                } else if (body instanceof LinkedHashMap) {
                    LinkedHashMap<?, ?> map = (LinkedHashMap<?, ?>) body;
                    if(map.get("status")==null){
                        return ResultVO.success(body);
                    }else {
                        int code = (int) map.get("status");
                        String msg = "request " + map.get("path") + " has " + map.get("error");
                        return ResultVO.fail(code, msg);
                    }
                } else {
                    return ResultVO.success(body);
                }
            }
        }
    }

    private String toJsonStr(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON格式化对象错误");
        }
    }

}
